package com.example.block_chain.controller.school;

import com.example.block_chain.RabbitMQ.Producer;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.common.SystemParameters;
import com.example.block_chain.domain.pbft.VoteInfo;
import com.example.block_chain.domain.pojo.School;
import com.example.block_chain.service.blockChain.BlockService;
import com.example.block_chain.utils.KeyValueReaderUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/*
 *@description: 学校相关接口
 *@author: hisen
 *@Time: 2024/3/8  15:04
 */
@RestController
public class SchoolController {

    @Resource
    BlockService blockService;

    @Resource
    Producer producer;

    @GetMapping("/getSchool")
    public ResponseResult getSchools() {
        List<School> school = KeyValueReaderUtil.getSchool(SystemParameters.SCHOOL_FILE_PATH);
        return ResponseResult.okResult(school);
    }

    @PostMapping("/addSchool")
    public ResponseResult addSchool(@RequestBody School school) {
        if (KeyValueReaderUtil.getDigestByCode(school.getSchoolCode(), SystemParameters.SCHOOL_FILE_PATH) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SCHOOL_EXISTS);
        }
        String str = school.getSchoolCode() + "=" + school.getSchoolName();
        KeyValueReaderUtil.addStringIntoFile(SystemParameters.SCHOOL_FILE_PATH, str);
        //学校上链
        VoteInfo voteInfo = blockService.createSchoolBlock(school.getSchoolCode());
        System.out.println(voteInfo);
        producer.sendMessage(voteInfo);

        return ResponseResult.okResult();
    }
}
